<?php

namespace App\Admin\Controllers\Keyword;

use App\Admin\Actions\Keyword\Add;
use App\Admin\Actions\Keyword\AutoSelect;
use App\Admin\Actions\Keyword\Derivative;
use App\Admin\Actions\Keyword\DerivativeForKeyword;
use App\Admin\Actions\Keyword\ShowDerivatives;
use App\Miya\Models\Area;
use App\Miya\Models\DerivativeKeyword;
use App\Miya\Models\Keyword;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Table;
use Illuminate\Support\Facades\Log;

class KeywordController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '主关键词管理';

    public function index(Content $content)
    {
        return $content
            ->title($this->title())
            ->description($this->description['index'] ?? trans('admin.list'))
            ->body($this->keywordCountLimit())
            ->body($this->grid());
    }

    protected function keywordCountLimit()
    {
        $max = config('keyword.max_count');
        $keywordCount = Keyword::count();
        if ($keywordCount > $max) {
            return view('miya::keywords.count_limit', ['max' => $max]);
        }
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Keyword());
        if (config('keyword.show_derivatives')) {
            $relations = ['area', 'derivatives.area'];
        } else {
            $relations = ['area'];
        }
        $grid->model()->with($relations)->withCount('derivatives');

        $grid->column('id', '序号');
        $grid->column('keyword', '关键词')->label();
        $grid->column('prefix', '词头')->display(function () {
            return count($this->prefix);
        })->modal('关键词词头', function ($model) {
            $data = [];
            $prefix = $model->prefix ?? [];
            collect($prefix)->each(function ($word) use (&$data) {
                $data[] = [$word];
            });
            return new Table(['词头'], $data);
        });
        $grid->column('suffix', '词尾')->display(function () {
            return count($this->suffix);
        })->modal('关键词词尾', function ($model) {
            $data = [];
            $suffix = $model->suffix ?? [];
            collect($suffix)->each(function ($word) use (&$data) {
                $data[] = [$word];
            });
            return new Table(['词尾'], $data);
        });
        $grid->column('area_id', '替换地区')->editable('select', Area::pluck('name', 'id'));

        if (config('keyword.show_derivatives')) {
            $grid->column('derivative_keywords', '衍生词')->display(function () {
                return $this->derivatives_count;
            })->modal('衍生关键词', function ($model) {
                $der = $model->derivatives->map(function ($data) {
                    $tableData = $data->only(['id', 'type', 'area_id', 'keyword']);
                    $tableData['type'] = DerivativeKeyword::$types[$data->type];
                    $tableData['area_id'] = $data->area->name ?? '';
                    return $tableData;
                })->toArray();

                return new Table(['序号', '类型', '地区', '衍生词'], $der);
            });
        } else {
            $grid->column('derivative_keywords', '衍生词')->display(function () {
                return $this->derivatives_count;
            })->label();
        }

        $grid->tools(function (Grid\Tools $tools) {
            $tools->append(new Add());
            $tools->append(new Derivative());
            $tools->append(new AutoSelect());
        });
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->add(new DerivativeForKeyword());
            $actions->add(new ShowDerivatives());

            $actions->disableView();
        });
        $grid->filter(function (Grid\Filter $filter) {
            $filter->disableIdFilter();
            $filter->like('keyword', '关键词');
        });
        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Keyword());

        $form->tab('基础设置', function (Form $form) {
            $form->text('keyword', '关键词')->rules(['required'])
                ->help('如果关键词中包含地区,请务必前往高级设置中,将包含的地区设为替换地区,否则生成关键词时,将无法正确识别地区!');
        })->tab('高级设置', function (Form $form) {
            $form->list('prefix', '词头')->value(explode(PHP_EOL, config('keyword.default_prefix')));
            $form->list('suffix', '词尾')->value(explode(PHP_EOL, config('keyword.default_suffix')));
            $areas = Area::all()->pluck('name', 'id');
            $form->select('area_id', '替换地区')->options($areas)->help('务必在这里选择关键词中出现需要替换的地区');
            $form->multipleSelect('ignore_areas', '排除地区')->options($areas)->help('例如:为避免出现如"从南京到南京物流"这样的衍生词,则将南京排除出被替换的地区');
        });

        return $form;
    }
}
